package com.hw.service.impl;

import com.hw.dao.MenuDao;
import com.hw.dao.RoleDao;
import com.hw.dao.UserDao;
import com.hw.entity.Menu;
import com.hw.entity.Role;
import com.hw.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;

/**
 * 获取用户相关信息
 *
 * @author F1335240
 * @version 1.0
 * @date 2020/5/11 9:20
 **/
@Service
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private MenuDao menuDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查用户
        User user = userDao.selectByUsername(username);
        log.info("UserDetailsService查询的用户：" + user);
        if (null != user) {
            //根据用户id查询用户角色
            List<Role> roles = roleDao.selectByUserId(user.getId());
            //填充权限
            Collection<SimpleGrantedAuthority> authorities = new HashSet<>();
            for (Role role : roles) {
                authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
            }
//            user.setUserRoles(roles);
            //填充权限菜单

            List<Menu> menuList = menuDao.selectByRoleId(roles);
//            user.setRoleMenus(menuList);
            return new User(username, user.getPassword(), menuList, authorities);
        } else {
            log.error(username + "不存在");
            throw new UsernameNotFoundException(username + "not found");
        }
    }
}
